import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Request } from 'express';
import { JwtService } from '@nestjs/jwt';
import { Reflector } from '@nestjs/core';
import { IS_PUBLIC_KEY } from '../../../common/decorators/public.decorator';
import {
  ACCOUNT_ID,
  ACCOUNT_ROLE_IDS,
} from '../../../common/constants/auth.constant';
import { ResponseMsgKey } from '../../../common/constants/api-response.constant';

export interface Payload {
  /**
   * userId or adminId
   */
  id: string;

  /**
   * token 生成时间（秒级时间戳）
   */
  iat: number;

  /**
   * token 过期时间（秒级时间戳）
   */
  exp?: number;

  /**
   * 系统角色id
   */
  roleIds: string[];
}

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private readonly jwtService: JwtService,
    private readonly reflector: Reflector,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) return true;
    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    try {
      const payload = await this.jwtService.verifyAsync<Payload>(token);
      request[ACCOUNT_ID] = payload.id;
      request[ACCOUNT_ROLE_IDS] = payload.roleIds;
    } catch {
      throw new UnauthorizedException(ResponseMsgKey.INVALID_TOKEN);
    }
    return true;
  }
  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
